import { createRouter, createWebHistory, type RouteLocationNormalized } from "vue-router";
import { routes } from "./routes";
import NProgress from "nprogress";
import { AxiosCanceler } from "@/api/helper/axiosCancel";
import { getQueryString } from "@/utils";
import { useAppStore } from "@/store/modules/app";

const axiosCanceler = new AxiosCanceler();

const router = createRouter({
	routes,
	history: createWebHistory()
});

export interface toRouteType extends RouteLocationNormalized {
	meta: {
		title?: string;
		noCache?: boolean;
	};
}

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	// 清除请求
	axiosCanceler.removeAllPending();

	// 获取url的userid保存
	const appStore = useAppStore();
	const userid = getQueryString("userid") ?? (to.query.userid as string);
	const userName = getQueryString("username") ?? (to.query.username as string);
	userid && appStore.setUser(userid, userName);

	// 重置滚动条
	window.scrollTo(0, 0);
	next();
});

/**
 * @description 路由跳转结束
 * */
router.afterEach(to => {
	document.title = (to.meta?.title as string) || "流程审批";
	NProgress.done();
});

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
	NProgress.done();
	console.warn(error.message);
});
export default router;
